package com.sky.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class SaltedEncryptionUtil {

    // 生成盐值
    public static byte[] generateSalt() {
        byte[] salt = new byte[16];
        try {
            SecureRandom secureRandom = SecureRandom.getInstanceStrong();
            secureRandom.nextBytes(salt);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return salt;
    }

    // 使用盐值对密码进行加密
    public static String encryptPassword(String password, byte[] salt) {
        String encryptedPassword = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(salt);
            byte[] hashedPassword = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hashedPassword) {
                sb.append(String.format("%02x", b));
            }
            encryptedPassword = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encryptedPassword;
    }

    // 验证密码是否匹配
    public static boolean verifyPassword(String password, byte[] salt, String hashedPassword) {
        String encryptedPassword = encryptPassword(password, salt);
        return encryptedPassword.equals(hashedPassword);
    }

    // 示例用法
    public static void main(String[] args) {
        String password = "123456";
        byte[] salt = generateSalt();
        String hashedPassword = encryptPassword(password, salt);
        System.out.println(hashedPassword);

        // 存储盐值和加密后的密码
        // ...

        // 验证密码
        boolean passwordMatch = verifyPassword(password, salt, hashedPassword);
        System.out.println("Password Match: " + passwordMatch);
    }
}